﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Xml.Linq;

namespace MyUtility
{
    public partial class TwitterPage : PhoneApplicationPage
    {
        public TwitterPage()
        {
            InitializeComponent();
        }

        private void bntLoadXML_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
			WebClient client = new WebClient();
			client.DownloadStringCompleted +=new System.Net.DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
        	client.DownloadStringAsync(new Uri("http://micthailand.net/wp7/camp/files/ppongsakorn.xml",UriKind.RelativeOrAbsolute));
		}

        private void client_DownloadStringCompleted(object sender, System.Net.DownloadStringCompletedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
			//e.Result;
			
			/* Sample Data
			TwitterPost p1 = new TwitterPost();
			p1.DatePosted = "Mon Sep 12 16:01:14 +0000 2011";
			p1.UserImage = "http://a1.twimg.com/profile_images/918535335/Pong-Thailand_normal.jpg";
			p1.PostText = "วันนี้วันพร http://t.co/Nlt4ECq";
			
			TwitterPost p2 = new TwitterPost();
			p2.DatePosted = "Mon Sep 12 16:01:14 +0000 2011";
			p2.UserImage = "http://a1.twimg.com/profile_images/918535335/Pong-Thailand_normal.jpg";
			p2.PostText = "วันนี้วันพระ http://t.co/Nlt4ECq";
			
			List<TwitterPost> l  = new List<TwitterPost>();
			l.Add(p1);
			l.Add(p2);
			l.Add(p1);
			l.Add(p2);
			l.Add(p1);
			l.Add(p2);
			l.Add(p1);
			l.Add(p2);
			
			tweetsListBox.ItemsSource = l;
			*/
			
			XElement TweetElement = XElement.Parse(e.Result);
			var postList = from tweet in TweetElement.Descendants("status")
						   select new TwitterPost{
							  	UserImage = tweet.Element("user").Element("profile_image_url").Value,
								PostText = tweet.Element("text").Value,
								DatePosted = tweet.Element("created_at").Value
							};
						
			tweetsListBox.ItemsSource = postList;
			
        }
    }
}
